<?php
namespace app\common\service;

/**
 * 支付宝支付
 */
use alipay\aop\AopClient;
use alipay\aop\request\AlipayTradeWapPayRequest;
use alipay\aop\request\AlipayTradeRefundRequest;
use think\facade\Db;

Class AliPay
{
    protected $alipay = [
        //应用ID,您的APPID。
        'app_id' => "2021001162643463",

        //商户私钥, 请把生成的私钥文件中字符串拷贝在此
        'merchant_private_key' => "MIIEogIBAAKCAQEAgQhbs1OEule1jn1WfNwY06sD8ULj4WmJtsnx9p8joNwb7QHTkbsJUkEDki5O+YaAZ71gVkfKjUxOEm02BwrXZxSts3WhjfJVhfaHiq1rEGPerXUJ8+pnLSx2RyOiDbaPXAagOUbG4aZPtIC+u49k+Y5YqxQQpNQHcjlg0xO+2F/o+xDh8e39tIHpvmtXULozMZFVqPWFC8eHXoJ6OZ8d/xHFuWYEny+GoEOUNwobHfbMFXFFMD5ZdVebPBjZIorym4NdjCNiQ0Wz17+uYpmnX75mLFalKg+qJD384hRt+hEgebBL1NVZi6nL/b+2wbudFjuHSjxXbGtfl6iY6NJNKwIDAQABAoIBAAlAayrJczvVLBxiWkArm9AZc/fpfuNbqNclVacENA7FmW798YiCa6GtLa9eiKUVgsFtb6ngDeLhtLtXf0cz/MvUTLwQVBwUYxNu4LsNwh5zurSfLq6BgRJZHMXvBSCMlWzYwMY6j+n//bkIfiR+nJPUJAFoN+VJmpsTCCE6SjXDWKRIrebk9RmyD4kBgZnb3XzMYHE2AIRw5dBF9PvhKtUiJ1Q8J0N6EHejVpKDT31Xrp9J4F3i/4H/bLDpS7RK+kD1yV8cBNjnICXu8YSictGOMmR/D/7huciBnL9hpJAc/hhR2ofilzEqtfHsJUJT1arcPzHfiHSv/VvkFT/YkbECgYEAueVEDaA4oJ8/FrjONuiQtJN1I3FGQIVd2bLph0H6pT8W1C9AXzfdsrrDuwsuCsQNnb8QpbQY1Q/c0ErNeGPJHnhSkokTrgw96crJZG3KdrRDEGvfN2K0Ik4iXgTlsRjnE3+O8iQyno76VtPLNezhSi1/yYFUgoD6It3oxnSD7lMCgYEAsbFuWfsl3UrqLF1uySo/bli13sbxJf4HDmq5g5C43N3/0k02ZhBaKokO2JSFftra2tJYlCqEIHscnUUxoUWAshdP1A+t6lFKhipuOoHN94U8d99wz1rZZZxIjW5Lj4LiWBZodFhDVRGcYjmV+JtDQIL4UdqgViIrjh/t2YphWskCgYBVZUaf48xfrQf0Ti0c+DURXvPetjiJhzqXuSKiKeMUaij4jERL+YP0iOtFT1t1Qp7mqlDhbhxCNClB3jsJZP2M68Uy35mUyLbgYXGmmvD5GtH8BzHhZYxOfgo3mpRRiJkOUfi+r3Y5dID3xg+B1DGiO8iKLsk9sjY2Mi6ui/PXVQKBgEDxJ/Oa5mvKRWuRejvrRON/aHjTHK9V+B48wzBiZC3UtPqXXZpPv6RsExD0txV1xybSWa1NHJ0CYaLY9xqJ3E86VeKbGGTa8PG38DFR34TnHQJylzgxa+LHC30lIliA7VhkWCitWW5t0UnU4grKM/oP49GGpbLVKjX3VWZ8PLiBAoGAGXGlzy1/GmhXtIpfIsDuBRJTJpVGz2cQe/lrHxQwzZXq3fQBzjX6V/noNIu1LPDDHSD4y9pYArYZUVBjd9ceVzh5dUnfEHICBpGNS8rBpUNmjf8YDlgp9nDxlkE2zorphm3EasLZouhh5RR8zBboklKu3s5rXQy5XwMycbfO2d0=",

        //异步通知地址
        'notify_url' => 'http://cmzx.dcpxjypt.cn/index.php/api/order/alipay_notify',
        'return_url' => "http://cmzx.dcpxjypt.cn/h5/#/pages/mine/ords/detail/success",

        //编码格式
        'charset' => "UTF-8",

        //签名方式
        'sign_type'=>"RSA2",

        //支付宝网关
        'gatewayUrl' => "https://openapi.alipay.com/gateway.do",

        //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
        'public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgQhbs1OEule1jn1WfNwY06sD8ULj4WmJtsnx9p8joNwb7QHTkbsJUkEDki5O+YaAZ71gVkfKjUxOEm02BwrXZxSts3WhjfJVhfaHiq1rEGPerXUJ8+pnLSx2RyOiDbaPXAagOUbG4aZPtIC+u49k+Y5YqxQQpNQHcjlg0xO+2F/o+xDh8e39tIHpvmtXULozMZFVqPWFC8eHXoJ6OZ8d/xHFuWYEny+GoEOUNwobHfbMFXFFMD5ZdVebPBjZIorym4NdjCNiQ0Wz17+uYpmnX75mLFalKg+qJD384hRt+hEgebBL1NVZi6nL/b+2wbudFjuHSjxXbGtfl6iY6NJNKwIDAQAB',   // 加密方式： **RSA2**

    ];

    /**
     * 开放当前实例属性
     * @return array
     */
    public function get_alipay()
    {
        return $this->alipay;
    }

    /**
     * 生成支付宝订单
     * @param $order_sn
     * @param $price
     * @param $extend_params
     * @param $store
     * @param $type
     * @return string
     */
    public function index($order_sn, $price, $extend_params,$store,$type)
    {

        $biz_content = json_encode([
            'out_trade_no'=> $order_sn,
            'product_code'=> 'FAST_INSTANT_TRADE_PAY',
            'total_amount'=> 0.01,
            'subject'=> 'BI8EJM Alipay 测试',
            'timeout_express'=>'30m',
            //'extend_params'=>$extend_params.'|'.$store.'|'.$type,

        ]);


        $aop = app('alipay\aop\AopClient');
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = $this->alipay['app_id'];
        //$aop->method = 'alipayTradePagePay';
        $aop->method = 'alipayTradeWapPay';
        $aop->charset = 'GBK';
        $aop->signType = 'RSA2';

        $aop->alipayrsaPublicKey = $this->alipay['public_key'];
        $aop->rsaPrivateKey      = $this->alipay['merchant_private_key'];
        //$payRequest= new AlipayTradePagePayRequest();
        $payRequest= new AlipayTradeWapPayRequest();

        $payRequest->setReturnUrl($this->alipay['return_url']);
        $payRequest->setNotifyUrl($this->alipay['notify_url']);
        $payRequest->setBizContent($biz_content);
        //$response = $aop->pageExecute($payRequest);
        $response = $aop->pageExecute($payRequest);
        //dd($response);
       //$content = 'https://openapi.alipay.com/gateway.do?'.$response;
        return $response;
    }


    public function refund($id)
    {

        $order = Db::name('order')->where('id',$id)->field('alipay_trade_no,order_sn')->find();

        $aop = new AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $this->alipay['app_id'];
        $aop->rsaPrivateKey = $this->alipay['merchant_private_key'];
        $aop->alipayrsaPublicKey = $this->alipay['public_key'];
        $aop->apiVersion = '1.0';
        $aop->signType = "RSA2";
        $aop->postCharset = 'UTF-8';
        $aop->format = "json";
        $request = new AlipayTradeRefundRequest();

        //需要传入的参数变量
        $trade_no  = $order['alipay_trade_no'];
        $refund_fee = 0.01;
        $out_trade_no = $order['order_sn'];

        $request->setBizContent("{" .
            "\"trade_no\":\"{$trade_no}\"," . //支付宝交易号，和商户订单号不能同时为空 特殊可选
            "\"out_trade_no\":\"{$out_trade_no}\"," .  //订单支付时传入的商户订单号,不能和 trade_no同时为空。 特殊可选
            "\"refund_amount\":\"{$refund_fee}\"," . //需要退款的金额，该金额不能大于订单金额,单位为元，支持两位小数     必选
            "\"refund_reason\":\"订单取消-退款\"" . //退款的原因说明    正常退款 可选 最后的“，”逗号去掉
            "}");


        $result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";


        $resultCode = $result->$responseNode->code;

        if(!empty($resultCode) && $resultCode == 10000){
            //退款成功,处理订单状态以及更新退款等信息

             return true;
            //return json(['code'=>200,'msg'=>'退款成功']);
        } else {
            return false;
            //return json(['code'=>400,'msg'=>'退款失败']);
        }

    }

   }